package com.ag.utils.param.verify;

import org.apache.commons.lang.StringUtils;

import com.ag.exception.InvalidParamException;
import com.ag.exception.SysTipsException;
import com.ag.utils.AgAssert;
import com.ag.utils.param.IVerifyAndConvertValue;

public class StringLengthVerifyAndConvertValue implements IVerifyAndConvertValue {
	int minLen;
	int maxLen;
	
	public StringLengthVerifyAndConvertValue(int minLen, int maxLen) {
		this.minLen = minLen;
		this.maxLen = maxLen;
	}
	
	@Override
	public Object getValue(Object value, String viewName, Object defaultValue) {
		boolean isValid = lengthIsValid(value == null ? null : String.valueOf(value), minLen, maxLen);
		if(!isValid) {
			throw new InvalidParamException(viewName + "长度请在" + minLen + "-" + maxLen + "之间.");
		}
		
		return value;
	}
	
	 public static boolean lengthIsValid(String str, int minLen, int maxLen) {
		 	AgAssert.isTrue(minLen <= maxLen, SysTipsException.class, "参数校验有误");
		 	
			if (StringUtils.isBlank(str)) {
				return minLen == 0;
			}

			if (str.length() > maxLen || str.length() < minLen) {
				return false;
			}

			return true;
		}
}
